package net.maku.controller;

import org.apache.commons.lang3.StringUtils;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import cn.binarywang.wx.miniapp.util.WxMaConfigHolder;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.AllArgsConstructor;
import me.chanjar.weixin.common.error.WxErrorException;
import net.maku.bean.param.WeixinParam;
import net.maku.bean.query.WebUserQuery;
import net.maku.utils.JsonUtils;
import net.maku.utils.WeChatDecrypt;

@RestController
@AllArgsConstructor
@Tag(name="微信信息处理")
public class WxMaUserController {

	private final WxMaService wxMaService;

    /**
     * 登陆接口
     */
	@Operation(summary = "微信登录")
    @RequestMapping("/weixinlogin")
    public String login( @RequestBody @Valid WeixinParam query){
        if (StringUtils.isBlank(query.getCode())) {
            return "empty jscode";
        }
        System.out.println("appid: " + query.getAppid() );
        System.out.println("code:  " + query.getCode()  );
        if (!wxMaService.switchover( query.getAppid() )) {
            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", query.getAppid()));
        }
        try {
            WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(query.getCode());
            System.out.println(session.getSessionKey());
            System.out.println(session.getOpenid());
            System.out.println( session.toString());
            System.out.println( JsonUtils.toJson(session) );
            
            //TODO 可以增加自己的逻辑，关联业务相关数据
            //return JsonUtils.toJson(session);


            WxMaUserInfo userInfo = wxMaService.getUserService().getUserInfo( session.getSessionKey(),
            		query.getEncryptedData(), query.getIv() );
            WxMaConfigHolder.remove();//清理ThreadLocal
            System.out.println( JsonUtils.toJson(userInfo) );
            
            
            String str = WeChatDecrypt.decrypt(query.getEncryptedData(), session.getSessionKey(), query.getIv() );
            System.out.println( str );
            //wxMaService.getUserService().getUserInfo(null, null, null)
        } catch (WxErrorException e) {
            ///log.error(e.getMessage(), e);
            return e.toString();
        } finally {
            //WxMaConfigHolder.remove();//清理ThreadLocal
        }
        return "";
    }
    
    
    @GetMapping("/info")
    @Operation(summary = "获取微信登录信息")
    @RequestMapping("/info")
    public String info( @RequestBody @Valid WeixinParam query){
    //public String info( String appid, String sessionKey,
    //                   String signature, String rawData, String encryptedData, String iv) {

    System.out.println("==================info========================");
    if (!wxMaService.switchover(query.getAppid())) {
            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", query.getAppid()));
        }

        // 用户信息校验
    /*
        if (!wxMaService.getUserService().checkUserInfo( query.getSessionKey(), 
        		query.getRawData(), query.getSignature() ) ) {
            WxMaConfigHolder.remove();//清理ThreadLocal
            return "user check failed";
        }*/

        // 解密用户信息
        WxMaUserInfo userInfo = wxMaService.getUserService().getUserInfo(query.getSessionKey(), 
        	query.getEncryptedData(), query.getIv() );
        WxMaConfigHolder.remove();//清理ThreadLocal
        System.out.println( JsonUtils.toJson(userInfo) );
        return JsonUtils.toJson(userInfo);
    }
    
    
    
    
}
